package com.ilearn.iodata.iolingo.service;

import com.ilearn.iodata.iolingo.utils.OlingoUtil;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

@Service
public class GetEntityService {


    @Autowired
    ApiKeysService apiKeysService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    public class EntityRowMapper implements RowMapper {

        private String entitySetName;

        private List<EdmKeyPropertyRef> keyPropertyRefs;

        public EntityRowMapper(){}

        public EntityRowMapper(String entitySetName, List<EdmKeyPropertyRef> keyPropertyRefs) {
            this.entitySetName = entitySetName;
            this.keyPropertyRefs = keyPropertyRefs;
        }

        @Nullable
        @Override
        public Entity mapRow(ResultSet rs, int rowNum) throws SQLException {

            Entity entity = new Entity();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String key = rsmd.getColumnLabel(i);
                Object value = rs.getObject(i);

                Property property = new Property(null, key, ValueType.PRIMITIVE, value);

                entity.addProperty(property);
            }

            OlingoUtil.createId(entitySetName, entity, keyPropertyRefs);

            return entity;
        }


    }


    public Entity getEntityByJdbcTemplate(String sql, String entitySetName, List<EdmKeyPropertyRef> keyPropertyRefs){

        Entity entity = (Entity) jdbcTemplate.queryForObject(
                sql, new Object[] {}, new EntityRowMapper(entitySetName, keyPropertyRefs));
        return entity;
    }

}
